/*
 *  贴图填充立方体
*/
#include <stdio.h>
#include <unistd.h>

#include "3d_window.h"
#include "util_bmp.h"
#include "util_delay.h"

Image* GetImageFromBmp(const char* bmpFile)
{
    uint32_t width, height;
    uint8_t* mem = NULL;
    mem = UtilBmpGetBGRA(bmpFile, &width, &height, NULL);
    return mem ? new Image(width, height, IMAGE_FORMAT_BGRA, mem) : NULL;
}

int main(void)
{
    D3Window window(300, 300);
    D3Model model1, model2;

    Image* image = GetImageFromBmp("../../resource/test/cover.bmp");
    ImageGrid* imageGrid = NULL;
    if (image)
        imageGrid = new ImageGrid(*image);

    //空间坐标轴(x红,y绿,z蓝)
    model1.AddLine(
        -1, 0, 0,
        1, 0, 0,
        0xFF0000);
    model1.AddLine(
        0, -1, 0,
        0, 1, 0,
        0x00FF00);
    model1.AddLine(
        0, 0, -1,
        0, 0, 1,
        0x0000FF);
    //模型放大100倍,例如顶点坐标(1,-1,1)则变成(100,-100,100)
    model1.Zoom(100);

    //没有上下封盖的正方体(其中2面使用贴图)
    model2.AddRect(
        1, -1, 1,
        1, 1, 1,
        1, 1, -1,
        1, -1, -1,
        0x80FF0000,
        imageGrid);
    model2.AddRect(
        -1, -1, 1,
        -1, 1, 1,
        -1, 1, -1,
        -1, -1, -1,
        0x8000FF00,
        imageGrid);
    model2.AddRect(
        1, 1, 1,
        1, 1, -1,
        -1, 1, -1,
        -1, 1, 1,
        0x800000FF);
    model2.AddRect(
        1, -1, 1,
        1, -1, -1,
        -1, -1, -1,
        -1, -1, 1,
        0x80FFFF00);
    //模型放大
    model2.Zoom(50);

    //模型添加到3D窗口
    window.AddModel(&model1);
    window.AddModel(&model2);

    //相机位置和角度(模型在原点处,移动相机)
    window.SetLocation(-300, -300, 100); //向右、后方向各移动300,并抬高100
    window.SetDirection(-12, 45, 0); //往左手方向转45度,向下俯角12度

    while (1)
    {
        //从窗口截取图片并保存到bmp
        Image tmpImg = window.GetImage();
        UtilBmpCreate("./out.bmp", tmpImg.Mem().addr, tmpImg.Width(), tmpImg.Height(), tmpImg.Pb());
    
#if 1
        //不断旋转模型
        model2.sites.RollSelf(11, 7, 3);

        //一帧延时
        UtilDelayMs(500);
#else
        char in = getc(stdin);
        printf("input: [%d] \r\n", in);
        switch(in)
        {
            //以自己为中心上下左右旋转相机
            case 'w':
                window.RollSelf(2, 0, 0);
                break;
            case 's':
                window.RollSelf(-2, 0, 0);
                break;
            case 'a':
                window.RollSelf(0, 2, 0);
                break;
            case 'd':
                window.RollSelf(0, -2, 0);
                break;
            //前后移动相机
            case 'q':
                window.MoveSelf(20, 0, 0);
                break;
            case 'e':
                window.MoveSelf(-20, 0, 0);
                break;
            //正前方轴向旋转
            case 'z':
                window.RollSelf(0, 0, 5);
                break;
            case 'c':
                window.RollSelf(0, 0, -5);
                break;
        }
#endif
    }

    if (imageGrid)
        delete imageGrid;
    if (image)
        delete image;
    return 0;
}
